//
//  TTDetailFilterViewController.m
//  TaoTuo
//
//  Created by admin on 2019/8/28.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTPairDetailFilterViewController.h"
#import "TTDetailFilterExistView.h"
#import "TTDetailFliterCustomView.h"
#import "TTGoodsDetailViewController.h"
#import "TTXianhuoModel.h"
#import "TTDetailFilterDingzhiView.h"

#define topBtnBaseTag 222222

@interface TTPairDetailFilterViewController ()
{
    CGFloat h;
    CGFloat top;
}

@property (nonatomic, strong) TTDetailModel *model;
@property (nonatomic, strong) UIButton *existBtn;   // 现货按钮
@property (nonatomic, strong) UIButton *customBtn;   // 定制按钮
@property (nonatomic, strong) TTDetailFilterExistView *manExistView;
@property (nonatomic, strong) TTDetailFilterExistView *womanExistView;
@property (nonatomic, strong) TTDetailFliterCustomView *customView;
@property (nonatomic, strong) TTDetailFilterDingzhiView *dingzhiView;
@property (nonatomic, strong) UIView *footerView;
@property (nonatomic, strong) UIButton *confirmBtn;
///选中的按钮
@property (nonatomic, strong) UIButton *selectBtn;
@property (nonatomic, strong) UIScrollView *scrollView;

///记录刚进来时选中的商品
@property (nonatomic, strong) NSMutableDictionary *existViewSelectDic;

/// 有多少可定制的产品
@property (nonatomic, assign) NSInteger customCount;
///根据条件过滤掉的数量
@property (nonatomic, assign) int stockFilterCount;

@property (nonatomic, strong) UIView *yellowView;

@property (nonatomic, strong) TTXianhuoModel *xianhuoModel;
@property (nonatomic, strong) NSDictionary *parmasDic;
///默认选中的index标签
@property (nonatomic, assign) NSInteger defaultIndex;

@end

@implementation TTPairDetailFilterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    h = self.view.height * 0.85;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismiss) name:detailFilterViewControllerDismiss object:nil];
    
}


- (void)dismiss
{
    for (TTDetailStockListModel *model in self.manExistView.selectArray) {
        model.selected = NO;
    }
    for (TTDetailStockListModel *model in self.womanExistView.selectArray) {
        model.selected = NO;
    }
    for (TTDetailStockListModel *model in self.customView.selectArray) {
        model.selected = NO;
    }
    
    for (NSString *key in self.existViewSelectDic.allKeys) {
        TTDetailStockListModel *model = self.existViewSelectDic[key];
        model.selected = YES;
    }
    
    
    [self dismissViewControllerAnimated:YES completion:nil];
}


- (void)setModel:(TTDetailModel *)model datasArray:(NSArray *)datasArray selectArray:(nonnull NSArray *)selectArray customCount:(NSInteger)customCount stockFilterCount:(int)stockFilterCount
{
    self.model = model;
    self.customCount = customCount;
    self.stockFilterCount = stockFilterCount;
    
    // 添加选中的
    [self.existViewSelectDic removeAllObjects];
    [self.manExistView.selectArray removeAllObjects];
    [self.womanExistView.selectArray removeAllObjects];
    for (TTDetailStockListModel *model in selectArray) {
        if (model.selected && model.StockType == 0) {
            [self.existViewSelectDic setObject:model forKey:model.GoodsBarCode];
        }
    }
    
    [self setCellContentWithModel:model dataArray:datasArray];
    
    [self setupSubviewsWithDatasArray:datasArray selectArray:selectArray];
    
}

- (void)setCellContentWithModel:(TTDetailModel *)model dataArray:(NSArray *)dataArray
{
    for (TTDetailStockListModel *slModel in dataArray) {
        // 行间距
        NSString *contentStr = [slModel.GoodsAttr componentsJoinedByString:@"\n"];
        NSMutableAttributedString *contentAttr = [[NSMutableAttributedString alloc] initWithString:contentStr];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.lineSpacing = 5;
        [contentAttr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, contentStr.length)];
//        CGFloat contentW = SCREEN_WIDTH >= 375 ? 290 * kScale : 270 * kScale;
        CGFloat contentW = SCREEN_WIDTH - 15;
        CGFloat h = [contentStr boundingRectWithSize:CGSizeMake(contentW, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:12], NSParagraphStyleAttributeName : style} context:nil].size.height + 20 + 20;
        slModel.h = h;
    }
}


// 确定按钮点击了
- (void)confirmBtnClick
{
    NSMutableArray *allSelectedArray = [NSMutableArray array];
    
    BOOL canClick = NO;
    for (TTDetailStockListModel *model in self.manExistView.selectArray) {
        if (model.selected) {
            canClick = YES;
            [allSelectedArray addObject:model];
        }
    }
    for (TTDetailStockListModel *model in self.womanExistView.selectArray) {
        if (model.selected) {
            canClick = YES;
            [allSelectedArray addObject:model];
        }
    }
    
    for (TTDetailStockListModel *model in self.customView.selectArray) {
        if (model.selected) {
            canClick = YES;
            [allSelectedArray addObject:model];
        }
    }
    
    
    if ([self.confirmBtn.titleLabel.text isEqualToString:@"提交"]) {
        
        if ([self.dingzhiView canCommit]) {
            // 提交定制
            [self confirmCustomData];
        }
        
        if (allSelectedArray.count > 0) {
            
            for (TTDetailStockListModel *model in allSelectedArray) {
                model.selected = YES;
            }
            
            if (self.selectCompleteBlock) {
                self.selectCompleteBlock(allSelectedArray);
            }
        }
        
    } else {
        if (!canClick) {
            [self.view makeToast:@"请选择货品" duration:1.0 position:CSToastPositionCenter];
            return;
        }
        
        if (self.selectCompleteBlock) {
            self.selectCompleteBlock(allSelectedArray);
        }
        
        [self dismissViewControllerAnimated:YES completion:nil];
    }
    
    
    
}

- (void)confirmCustomData
{
    [self.dingzhiView.dic setObject:self.dingzhiView.tf.text forKey:@"param.lettering"];
    [self.dingzhiView.dic setObject:self.dingzhiView.textView.text forKey:@"param.content"];
    [self.dingzhiView.dic setObject:self.styleLibraryId forKey:@"param.styleLibraryId"];
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postUrlString:addCustomData_api parameters:self.dingzhiView.dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [MBProgressHUD showSuccess:@"提交成功"];
        [self dismissViewControllerAnimated:YES completion:nil];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}


///请求男戒或女戒的数据
- (void)getOtherGenderData
{
    TTDetailFilterExistView *existView = [self.model.Gender isEqualToString:@"女"] ? self.manExistView : self.womanExistView;
    if (self.model.RelationStandardNumber.length == 0) {
        [existView setModel:nil dataArray:nil];
        return;
    }
    NSString *isOldUser = [TTLoginSingle sharedSingle].userModel.IsOldUser ? @"true" : @"false";
    
    NSDictionary *dic = @{
        @"param.finishedProduct" : @(0),
        @"param.isOldUser" : isOldUser,
        @"param.standardNumber" : self.model.RelationStandardNumber
    };
    NSMutableDictionary *mDic = dic.mutableCopy;
    if (self.xianhuoOtherParams) {
        [mDic addEntriesFromDictionary:self.xianhuoOtherParams];
    }
    //如果是显示所有数据使用dic
    NSDictionary *parmasDic = self.allShopShow ? dic : mDic;
    if (self.parmasDic.allKeys.count == parmasDic.allKeys.count) {
        return;
    }
    
    self.parmasDic = parmasDic;
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] requestMethod:GET urlString:getXianhuo_api parameters:parmasDic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        self.xianhuoModel = [TTXianhuoModel modelWithJSON:responseObject];
        
        [self setCellContentWithModel:self.model dataArray:self.xianhuoModel.StockList];
        
        for (TTDetailStockListModel *model in self.xianhuoModel.StockList) {
            TTDetailStockListModel *sModel = self.existViewSelectDic[model.GoodsBarCode];
            if (sModel) {
                model.selected = YES;
                [existView.selectArray addObject:model];
            }
        }
        
        [existView setModel:self.model dataArray:self.xianhuoModel.StockList];
        
        NSString *title = [NSString stringWithFormat:@"已根据搜索过滤%d件现货，显示全部", self.stockFilterCount];
        NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:title];
        [attrTitle addAttributes:@{NSForegroundColorAttributeName : UIColorHex(#FE7575), NSUnderlineStyleAttributeName : @1} range:[title rangeOfString:@"显示全部"]];
        UIButton *btn = self.yellowView.subviews.firstObject;
        [btn setAttributedTitle:attrTitle forState:UIControlStateNormal];
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
        [existView setModel:nil dataArray:nil];
        
    } showLoadingInView:existView];
}

- (void)topBtnClick:(UIButton *)sender
{
    sender.selected = YES;
    self.selectBtn.selected = NO;
    self.selectBtn = sender;
    
    [self.confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    
    if ([sender.titleLabel.text isEqualToString:@"男戒"] || [sender.titleLabel.text isEqualToString:@"女戒"]) {
        if (!self.allShopShow) {
            self.yellowView.hidden = self.stockFilterCount == 0;
            if (!self.yellowView.hidden) {
                self.footerView.frame = CGRectMake(0, h - 75 - Tabbar_Bottom_height, self.view.width, 75 + Tabbar_Bottom_height);
                self.confirmBtn.top = self.yellowView.bottom;
            }
        }
    } else {
        self.yellowView.hidden = YES;
        self.footerView.frame = CGRectMake(0, h - 45 - Tabbar_Bottom_height, self.view.width, 45 + Tabbar_Bottom_height);
        self.confirmBtn.top = 0;
        
        if ([sender.titleLabel.text isEqualToString:@"定制"]) {
            [self.confirmBtn setTitle:@"提交" forState:UIControlStateNormal];
        }
    }
    
    NSInteger tag = sender.tag - topBtnBaseTag;
    [self.scrollView setContentOffset:CGPointMake(self.view.width * tag, 0) animated:YES];
    
//    if (![sender.titleLabel.text isEqualToString:@"下单"] && ![sender.titleLabel.text hasPrefix:self.model.Gender]) {
//        [self getOtherGenderData];
//    }
    
}

///显示所有商品
- (void)showAllShopAction:(UIButton *)sender
{
    self.allShopShow = YES;
    [MBProgressHUD showLoadingAnimationOnView:[UIApplication sharedApplication].keyWindow];
    @weakify(self)
    self.detailVC.lookAllGuigeData = YES;
    [self.detailVC getNetworkDataSuccessBlock:^(TTDetailModel * _Nonnull model, NSArray * _Nonnull canShowGuigeArray, NSArray * _Nonnull guigeArray, NSInteger customizedCount, int stockFilterCount) {
        @strongify(self)
        [MBProgressHUD dismissAnimationOnView:[UIApplication sharedApplication].keyWindow];
        [self setModel:model datasArray:canShowGuigeArray selectArray:guigeArray customCount:customizedCount stockFilterCount:stockFilterCount];
    }];
}


- (void)setupSubviewsWithDatasArray:(NSArray *)datasArray selectArray:(NSArray *)selectArray
{
    NSMutableArray *existArray = [NSMutableArray array];
    for (TTDetailStockListModel *model in datasArray) {
        if (model.StockType == 0) {
            [existArray addObject:model];
        }
    }
    
    
    NSArray *items;
    if (existArray.count > 0) {
        items = self.customCount > 0 ? @[@"男戒", @"女戒", @"下单", @"定制"] : @[@"男戒", @"女戒", @"定制"];
    } else if (self.customCount > 0) {
        items = @[@"下单", @"定制"];
    }
    
    self.defaultIndex = [self.model.Gender isEqualToString:@"男"] ? 0 : 1;
    if (self.selectDZ) {
        self.defaultIndex = items.count - 1;
    }
    
    UIButton *lastBtn;
    for (int i = 0; i < items.count; i++) {
        NSString *itemTitle = items[i];
        UIButton *btn = [UIButton createButtonWithTitle:itemTitle titleColor:UIColorHex(333333) titleFont:[UIFont systemFontOfSize:14] backgroundColor:[UIColor whiteColor] target:self action:@selector(topBtnClick:)];
        [btn setBackgroundImage:[UIImage imageNamed:@"graybg"] forState:UIControlStateNormal];
        [btn setBackgroundImage:[UIImage imageNamed:@"whitebg"] forState:UIControlStateSelected];
        btn.tag = topBtnBaseTag + i;
        btn.layer.cornerRadius = 5;
        btn.layer.masksToBounds = YES;
        btn.frame = CGRectMake(lastBtn.right + 1, 0, 75, 30);
        [self.view addSubview:btn];
        lastBtn = btn;
        
        if (i == self.defaultIndex) {
            btn.selected = YES;
            self.selectBtn = btn;
        }
    }
    
    top = items.count > 0 ? 27 : 0;
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, top, self.view.width, h - 45 - Tabbar_Bottom_height - top)];
    self.scrollView.contentSize = CGSizeMake(self.view.width * items.count, self.scrollView.height);
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.scrollView.scrollEnabled = NO;
    [self.view addSubview:self.scrollView];
    [self.scrollView setContentOffset:CGPointMake(self.view.width * self.defaultIndex, 0) animated:YES];
    
    if ([items containsObject:@"男戒"] || [items containsObject:@"女戒"]) {
        if ([self.model.Gender isEqualToString:@"女"]) {
            self.manExistView = [[TTDetailFilterExistView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.scrollView.height)];
            [self.scrollView addSubview:self.manExistView];
            self.womanExistView = [[TTDetailFilterExistView alloc] initWithFrame:CGRectMake(self.manExistView.right, 0, self.view.width, self.scrollView.height) model:self.model dataArray:existArray];
            [self.scrollView addSubview:self.womanExistView];
        } else {
            self.manExistView = [[TTDetailFilterExistView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, self.scrollView.height) model:self.model dataArray:existArray];
            [self.scrollView addSubview:self.manExistView];
            self.womanExistView = [[TTDetailFilterExistView alloc] initWithFrame:CGRectMake(self.manExistView.right, 0, self.view.width, self.scrollView.height)];
            [self.scrollView addSubview:self.womanExistView];
        }
        // 直接请求
        [self getOtherGenderData];
    }
    if ([items containsObject:@"下单"] || items == nil) {
        if (self.customCount > 0) {
            NSMutableArray *array = [NSMutableArray array];
            for (TTDetailStockListModel *model in selectArray) {
                if (model.selected && model.StockType == 2) {
                    [array addObject:model];
                }
            }
            self.customView = [[TTDetailFliterCustomView alloc] initWithFrame:CGRectMake(self.womanExistView.right, self.womanExistView.top, self.view.width, self.scrollView.height) model:self.model styleLibraryId:self.styleLibraryId selectArray:array];
            [self.scrollView addSubview:self.customView];
            
        }
    }
    
    CGFloat dingzhiViewLeft = [items containsObject:@"下单"] ? self.customView.right : self.womanExistView.right;
    self.dingzhiView = [[TTDetailFilterDingzhiView alloc] initWithFrame:CGRectMake(dingzhiViewLeft, self.womanExistView.top, self.view.width, self.scrollView.height) model:self.model styleLibraryId:self.styleLibraryId];
    [self.scrollView addSubview:self.dingzhiView];
    
    BOOL notShowYellowView = (self.allShopShow || existArray.count == 0 || self.stockFilterCount == 0);
    CGFloat footerH = notShowYellowView ? 45 : 75;
    self.footerView = [[UIView alloc] initWithFrame:CGRectMake(0, h - footerH - Tabbar_Bottom_height, self.view.width, footerH + Tabbar_Bottom_height)];
    self.footerView.backgroundColor = kMainColor;
    [self.footerView removeFromSuperview];
    [self.view addSubview:self.footerView];
    
    self.yellowView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 30)];
    self.yellowView.backgroundColor = UIColorHex(#FCCA59);
    [self.footerView addSubview:self.yellowView];
    
    NSString *title = [NSString stringWithFormat:@"已根据搜索过滤%d件现货，显示全部", self.stockFilterCount];
    NSMutableAttributedString *attrTitle = [[NSMutableAttributedString alloc] initWithString:title];
    [attrTitle addAttributes:@{NSForegroundColorAttributeName : UIColorHex(#FE7575), NSUnderlineStyleAttributeName : @1} range:[title rangeOfString:@"显示全部"]];
    UIButton *allShowBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    allShowBtn.titleLabel.font = [UIFont systemFontOfSize:11];
    [allShowBtn setTitleColor:UIColorHex(#666666) forState:UIControlStateNormal];
    [allShowBtn setAttributedTitle:attrTitle forState:UIControlStateNormal];
    [allShowBtn addTarget:self action:@selector(showAllShopAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.yellowView addSubview:allShowBtn];
    [allShowBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(10);
        make.top.height.equalTo(self.yellowView);
    }];
    
    self.yellowView.hidden = notShowYellowView;
    
    NSString *confirmTitle = self.selectDZ ? @"提交" : @"确定";
    CGFloat confirmBtnTop = notShowYellowView ? 0 : self.yellowView.bottom;
    self.confirmBtn = [UIButton createButtonWithTitle:confirmTitle titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:nil target:self action:@selector(confirmBtnClick)];
    self.confirmBtn.frame = CGRectMake(0, confirmBtnTop, self.view.width, 45);
    [self.confirmBtn removeFromSuperview];
    [self.footerView addSubview:self.confirmBtn];
    
    
    TTDetailFilterExistView *existView = [self.model.Gender isEqualToString:@"女"] ? self.womanExistView : self.manExistView;
    for (TTDetailStockListModel *model in existArray) {
        TTDetailStockListModel *sModel = self.existViewSelectDic[model.GoodsBarCode];
        if (sModel) {
            [existView.selectArray addObject:sModel];
        }
    }
    
    
    
}

- (NSMutableDictionary *)existViewSelectDic
{
    if (!_existViewSelectDic) {
        _existViewSelectDic = [NSMutableDictionary dictionary];
    }
    return _existViewSelectDic;
}



- (void)dealloc
{
    NSLog(@"[< %@ >] --> 释放了", self.className);
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
